// controllers/smsController.js
const SmsService = require('../services/SmsService');
const asyncHandler = require('../utils/asyncHandler');
const { successResponse, errorResponse } = require('../utils/response');
const Joi = require('joi');

class SmsController {
  /**
   * 发送验证码
   */
  static sendVerificationCode = asyncHandler(async (req, res) => {
    // 验证请求参数
    const schema = Joi.object({
      phone: Joi.string().pattern(/^1[3-9]\d{9}$/).required(),
      type: Joi.string().valid('LOGIN', 'REGISTER', 'RESET_PASSWORD', 'OTHER').required()
    });

    const { error, value } = schema.validate(req.body);
    
    if (error) {
      return res.status(400).json(errorResponse('参数验证失败', error.details[0].message));
    }

    try {
      const result = await SmsService.sendVerificationCode({
        phone: value.phone,
        type: value.type,
        ip: req.clientIP
      });

      res.status(200).json(successResponse({
        message: '验证码发送成功',
        logId: result.logId
      }));
    } catch (err) {
      res.status(500).json(errorResponse('短信发送失败', err.message));
    }
  });

  /**
   * 验证验证码
   */
  static verifyCode = asyncHandler(async (req, res) => {
    // 验证请求参数
    const schema = Joi.object({
      phone: Joi.string().pattern(/^1[3-9]\d{9}$/).required(),
      code: Joi.string().length(6).required(),
      type: Joi.string().valid('LOGIN', 'REGISTER', 'RESET_PASSWORD', 'OTHER').required()
    });

    const { error, value } = schema.validate(req.body);
    
    if (error) {
      return res.status(400).json(errorResponse('参数验证失败', error.details[0].message));
    }

    const isValid = await SmsService.verifyCode(value);

    res.status(200).json(successResponse({
      valid: isValid,
      message: isValid ? '验证码验证成功' : '验证码无效或已过期'
    }));
  });
}

module.exports = SmsController;